var AddThis_Util = {

    _prefComponent: null,

    dbg : function (text) {
        
    },
    
    navToUrl : function(url) {
        AddThis_Util.dbg("Util.navToUrl: naving to -> " + url);
        
        
        var open_newwindow = AddThis_Util.getIntegerPref("browser.link.open_newwindow", 3);
        var w;
        switch(open_newwindow)
        {
            case 1: 
                gBrowser.loadURI(url);
                w = window;
                break;
            case 2: 
                w = gBrowser.contentWindow.open(url);
                break;
            case 3: 
            default:
                gBrowser.selectedTab = gBrowser.addTab(url);
                w = gBrowser.contentWindow;
                break;
        }
        
        return w;
    },
    
    hasClass: function(el,cls) {
        return (el.className.search(new RegExp("(\\s|^)"+cls+"(\\s|$)")) != -1);
    },
    
    addClass: function(el,cls) {
        if (!AddThis_Util.hasClass(el,cls)) el.className += " " + cls;
    },
    
    removeClass: function(el,cls) {
        if (AddThis_Util.hasClass(el,cls)) {
            el.className=el.className.replace(new RegExp('(\\s|^)'+cls+'(\\s|$)'),' ');
        }
    },
   
    slash: function(str)
    {
        if (typeof str == "string") return str.replace(/(['"])/g,'\\$1');
        else return str;
    },
   
    resolveURL : function(baseUrl, relativeUrl)
    {
        try {
            var baseURLObj = this.convertURLToObject(baseUrl);
            return baseURLObj.resolve(relativeUrl);
        } catch(ex) {
            return relativeUrl;
        }
    },
    
    convertURLToObject : function(url)
    {
        var urlObj = Components.classes['@mozilla.org/network/standard-url;1'].createInstance(Components.interfaces.nsIURI);
        urlObj.spec = url; 
        return urlObj;
    },
    
    tumeric: function() {
        var args = [], i;
        for (i=0; i<arguments.length; i++) args.push(arguments[i]);
        var fn = args.shift();
        if(args.length >= fn.length) return fn.apply(this,args);
        return function()
        {
            var argss = [], i;
            for (i=0; i<arguments.length; i++) argss.push(arguments[i]);
            return fn.apply(this, args.concat(argss) ); 
        };
    },
    
    _getPrefComponent: function()
    {
        if (AddThis_Util._prefComponent == null)
        {
            AddThis_Util._prefComponent = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
        }
        return AddThis_Util._prefComponent;
    },
    
    getBooleanPref: function(name, defaultValue)
    {
        try {
            return AddThis_Util._getPrefComponent().getBoolPref(name);
        } catch(e) {
            return defaultValue;
        }
    },
    
    setBooleanPref: function(name, newValue) {
        AddThis_Util.dbg("setBooleanPref: setting " + name + " to " + newValue);
        AddThis_Util._getPrefComponent().setBoolPref(name, newValue);
        AddThis_Util.dbg("setBooleanPref: set");
    },
    
    getIntegerPref: function(name, defaultValue)
    {
        try {
            return AddThis_Util._getPrefComponent().getIntPref(name);
        } catch(e) {
            return defaultValue;
        }
    },
    
    setIntegerPref: function(name, newValue) {
        AddThis_Util.dbg("setIntegerPref: setting " + name + " to " + newValue);
        AddThis_Util._getPrefComponent().setIntPref(name, newValue);
        AddThis_Util.dbg("setIntegerPref: set");
    },
    
    getStringPref: function(name, defaultValue)
    {
        try {
            return AddThis_Util._getPrefComponent().getCharPref(name);
        } catch(e) {
            return defaultValue;
        }
    },
    
    setStringPref: function(name, newValue) {
        AddThis_Util.dbg("setStringPref: setting " + name + " to " + newValue);
        AddThis_Util._getPrefComponent().setCharPref(name, newValue);
        AddThis_Util.dbg("setStringPref: set");
    },
    
    clearPref: function(name)
    {
        try {
            return AddThis_Util._getPrefComponent().clearUserPref(name);
        } catch(e) {
            return false;
        }
    },
    
    getFirefoxVersion: function()
    {
        if (AddThis_Util._fxv == null)
        {
            var info = Components.classes["@mozilla.org/xre/app-info;1"] .getService(Components.interfaces.nsIXULAppInfo);
            AddThis_Util._fxv = info.version;
        }
        return AddThis_Util._fxv;
    },
    
    fxVersionAtLeast: function(ver)
    {
        var fxv = AddThis_Util.getFirefoxVersion();
        var vCheck = Components.classes["@mozilla.org/xpcom/version-comparator;1"].getService(Components.interfaces.nsIVersionComparator);  
        return (vCheck.compare(fxv, ver) >= 0);
    },
    
    getLocale: function() {
        var locale = AddThis_Util.getStringPref('general.useragent.locale','en-US');
        if (locale.length == 2)
        {
            var ll,ls,l;
            try {
                ll = AddThis_Util._getPrefComponent().getComplexValue('intl.accept_languages', Components.interfaces.nsIPrefLocalizedString).data;
            }
            catch(e) {
                ll == '';
            }
            if (ll == '') ll = AddThis_Util.getStringPref('intl.accept_languages',''); 

                ls = ll.split(',');
                for(var i in ls)
                {
                    l = ls[i].replace(/^\s+|\s+$/g, '');
                    if(l.length > 2 && l.substring(0,2)==locale)
                    {
                        locale=l;
                        break;
                    }
                }
        }
        return locale;
    },
    
    
    getActiveServicesObject: function()
    {
        AddThis_Util.dbg("getActiveServicesObject...");
        var i, so = {},
            serviceInclude = AddThis_Util.getStringPref('extensions.addthis.service.personal',''),
            services = serviceInclude.split(',');
        for(i=0; i< services.length; i++)
        {
            if (typeof AddThis_Constants.services[services[i]] !== "undefined") so[services[i]] = true;
        }
        return so;
    },
    
    
    loadServiceDefaults: function()
    {
        AddThis_Util.dbg("loadServiceDefaults...");
        
        var floc = AddThis_Util.getStringPref('general.useragent.locale','en-US'),
            aloc = floc.split('-',2),
            loc = aloc[0].toLowerCase();
            
        if (AddThis_Constants.serviceDefaults[loc] == undefined) loc = 'en';
        AddThis_Util.setStringPref('extensions.addthis.service.personal', AddThis_Constants.serviceDefaults[loc]);
        
    },
    
    png: function()
    {
        var d = new Date(), s = d.getTime(),
            o = AddThis_Util.getStringPref('extensions.addthis.session','');
        if (o=='' || o < (s - 86400000))
        {
            var u = AddThis_Constants.PT_SERVICE +
                    AddThis_Constants.PCO + "-" + AddThis_Constants.EXTENSION_VERSION +
                    "/auc/" + AddThis_Util._generateCuid() + ".gif?_uid=" + AddThis_Util.getCuid() +
                    "&sx=" + AddThis_Util._pngBool(AddThis_Search.isVisible()) +
                    "&bx=" + AddThis_Util._pngBool(AddThis_MainButton.isVisible()) +
                    "&tx=" + AddThis_Util._pngBool(AddThis_Toolbar.isVisible()) +
                    "&ux=" + AddThis_Util._pngBool(AddThis_UrlBar.isVisible()) +
                    "&cx=" + AddThis_Util._pngBool(AddThis_ContextMenu.isVisible());
                    
            AddThis_Util.dbg('png: ' + u);
            AddThis_Util._ajax(u);
            AddThis_Util.setStringPref('extensions.addthis.session',s); 
        }
    },
    
    _pngBool: function(v)
    {
        return (v===true) ? '1' : ((v===false) ? '0' : 'x');
    },
    
    _ajax: function(u)
    {
        var r = new XMLHttpRequest();
        r.onreadystatechange = function() {};
        r.open('GET',u,true);
        r.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;  
        r.send(null);
    },
    
    getCuid: function() {
        var c = AddThis_Util.getStringPref('extensions.addthis.cuid','');
        if (c=='')
        {
            c = AddThis_Util._generateCuid();
            AddThis_Util.setStringPref('extensions.addthis.cuid',c);
        }
        return c;
    },
    
    _generateCuid: function() { 
        var d = new Date(), z = '00000000',
            lo = Math.floor(Math.random() * (4294967295)); 
            hi = Math.floor(d.getTime() / 1000.0);
            
        lo = lo.toString(16);
        hi = hi.toString(16);
        
        lo = z.substring(0,8-lo.length) + lo;
        hi = z.substring(0,8-hi.length) + hi;
        
        return hi+lo;
    }
  
};

